package com.jerry.hm.algorithm.recursion;

import java.util.Arrays;

/**
 * 斐波那契数列
 *
 * @author Jerry
 * @since 2024/10/1 14:32
 */
public class Fibonacci {

    public static int fun(int n) {
        if (n == 0 || n == 1) {
            return n;
        }
        return fun(n - 1) + fun(n - 2);
    }

    /**
     * 记忆法优化
     *
     * @param n
     * @return
     */
    public static int fibonacci(int n) {
        int[] arr = new int[n + 1];
        Arrays.fill(arr, -1);
        arr[0] = 0;
        arr[1] = 1;
        return fun(n, arr);
    }

    public static int fun(int n, int[] cache) {
        if (cache[n] != -1) {
            return cache[n];
        }
        int x = fun(n - 1, cache);
        int y = fun(n - 2, cache);
        cache[n] = x + y;
        return cache[n];
    }
}
